package leetcode.code0501;

import java.util.ArrayList;
import java.util.List;

import leetcode.helper.tree.TreeNode;

public class Solution {

	int last;
	int cnt;
	int max;
	List<Integer> list;

	public int[] findMode(TreeNode root) {
		list = new ArrayList<>();
		last = 1000000;
		cnt = 0;
		max = 0;
		f(root);
		int[] ans = new int[list.size()];
		for (int i = 0; i < list.size(); i++) {
			ans[i] = list.get(i);
		}
		return ans;
	}

	private void f(TreeNode root) {
		if (root == null)
			return;
		f(root.left);
		int cur = root.val;
		if (cur == last) {
			cnt++;
		} else {
			last = cur;
			cnt = 1;
		}
		if (cnt > max) {
			list = new ArrayList<>();
			list.add(cur);
			max = cnt;
		} else if (cnt == max) {
			list.add(cur);
		}
		f(root.right);
	}
}
